<template>
  <el-dialog
    :width="props.width"
    :title="props.title"
    :close-on-click-modal="false"
  >
    <el-upload
      ref="uploadRef"
      action="#"
      :limit="1"
      :on-exceed="handleExceed"
      :auto-upload="false"
      :before-upload="beforeUpload"
      :on-change="handleChange"
    >
      <el-button type="success">选择文件</el-button>
      <template #tip>
        <div class="el-upload__tip" style="color: red">
          仅限上传1个文件, 选择新的文件将会覆盖原有的文件!
        </div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          style="float: left"
          type="primary"
          @click="
            close();
            confirm(dataList);
          "
          >确认上传
        </el-button>
        <el-button @click="close">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElLoading, ElMessage } from "element-plus";
import { ref } from "vue";
import { read, utils } from "xlsx";
import api from "@/utils";

export interface dialogProps {
  width?: string;
  title?: string;
  uploadUrl: string;
}

const props = withDefaults(defineProps<dialogProps>(), {
  width: "50%",
  title: "批量导入数据",
  uploadUrl: "",
});
const emit = defineEmits<{
  (
    e: "submit-json-format",
    data: Record<string, unknown>[][],
    callback: (
      value: Record<string, unknown>[],
      isSuccessFormat: boolean
    ) => void
  ): void;
  (e: "close"): void;
  (e: "get-record"): void;
}>();

// 关闭页面
const close = () => {
  emit("close");
};

// 获取数据
const confirm = (dataList: Record<string, unknown>) => {
  console.log(dataList);
  // 格式转化失败会传递空数组，如果dataList不是空数组则进行数据持久化
  if (JSON.stringify(dataList) !== "[]") {
    api.http
      .postJson(props.uploadUrl, dataList)
      .then(() => {
        emit("get-record");
      })
      .catch((err) => {
        console.log(err);
      });
  }
};
const uploadRef = ref();
const handleExceed = (files: File[]) => {
  ElMessage.warning("当前选择文件覆盖了之前选择的文件!");
  uploadRef.value.clearFiles();
  uploadRef.value.handleStart(files[0]);
};

const beforeUpload = (file: never) => {
  console.log("test");
  console.log(file);
};

const dataList = ref();
// 批量导入
const handleChange = (file: Record<string, unknown>) => {
  ElLoading.service({ text: "表格读取中..." });
  if (file) {
    try {
      let reader = new FileReader();
      reader.onload = (ev: ProgressEvent<FileReader>) => {
        const excelData = ev.target?.result;
        const wb = read(excelData, { type: "binary" });
        const data: Record<string, unknown>[][] = [];
        wb.SheetNames.forEach((sheetName: string, index: number) => {
          data[index] = utils.sheet_to_json(wb.Sheets[sheetName]);
        });
        emit(
          "submit-json-format",
          data,
          (value: Record<string, unknown>[], isSuccessFormat: boolean) => {
            dataList.value = value;
            if (!isSuccessFormat) {
              ElMessage.error({
                message: "表格字段不匹配或必填信息为空！",
              });
            } else {
              ElMessage.success({ message: "读取成功!" });
            }
          }
        );
      };
      reader.readAsArrayBuffer(file.raw as Blob);
    } catch (e) {
      console.log(e);
      ElMessage.error({ message: "读取失败!" });
    }
  }
  ElLoading.service().close();
};
</script>

<style scoped></style>
